<?php
    include('./config.php');
    include('./request.php');
    $username = $result->username;
    $goodsID = $result->goodsID;
    $goodsname = $result->goodsName;
    $goodsmodel = $result->goodsModel;
    $goodsprice = $result->goodsprice;
    $goods_num = $result->goods_num;
    $goods_date = $result->goods_date;
    $userID = $result->userID;
    $goodstype = $result->goods_type;
    $market_name = $result->market_name;
    $goodsAddress = $result->address;
    try{
        $pdo = new PDO($dsn,$user,$pass);
        $pdo->beginTransaction();
        $sql = "select * from goodsmodel where goods_id=".$goodsID." and goods_model='".$goodsmodel."'";
        $res = $pdo->prepare($sql);
        $res->execute();
        $rea = $res->fetch(PDO::FETCH_ASSOC);
     if($rea['goods_id']==$goodsID){
        $sql = "update goodsmodel set goods_num=goods_num-".$goods_num." where goods_id=".$goodsID." and goods_model='".$goodsmodel."' and goods_num>=".$goods_num;
        $res = $pdo->prepare($sql);
        $res->execute();
        if($res){
                $sql = "select * from goods where goods_id=".$goodsID;
                $res = $pdo->prepare($sql);
                $res->execute();
                $rea = $res->fetch(PDO::FETCH_ASSOC);
                if($rea['goods_name']==$goodsname){
                    $sql = "update goods set goods_num=goods_num-".$goods_num." where goods_id=".$goodsID;
                    $res = $pdo->prepare($sql);
                    $res->execute();
                    if($res){
                         $sql = "insert into purchaseorder(user_id,goods_id,goods_name,goods_model,goods_price,goods_num,market_name,goods_type,order_date,sendState,accState,adress)values(".$userID.",".$goodsID.",'".$goodsname."','".$goodsmodel."',".$goodsprice.",".$goods_num.",'".$market_name."','".$goodstype."','".$goods_date."','未发货','未收货','".$goodsAddress."')";
                         $res = $pdo->prepare($sql);
                         $res->execute();
                if($res){
                    echo "ok";
                    $pdo->commit();
                }else{
                    echo "error";
                    $pdo->rollBack();
                }
            }else{
                echo "error";
                $pdo->rollBack();
            }
        }else{
            echo "商品库存不足";
            $pdo->rollBack();
        }
    }else{
        echo "商品库存不足";
        $pdo->rollBack();
    }
    }else{
        echo "商品库存不足";
        $pdo->rollBack();
    }
    }catch(PDOException $e){
        $pdo->rollBack();
        echo "error";
    }
?>